/**
 * Created by PanJiaChen on 16/11/18.
 */

/**
 * Parse the time to string
 * @param {(Object|string|number)} time
 * @param {string} cFormat
 * @returns {string | null}
 */


// 格式化日期，fmt: yyyy-MM-dd hh:mm:ss
export default {
  // 导出的方法  tHeader => 设置Excel的表格第一行的标题  filterVal => 对象的属性key值 被导出listData => 导出数据  => 导出(文件)名称

  outExportExcel(tHeader = [], filterVal = [], listData = [], exportName = new Date().getTime()) {
    require.ensure([], () => {
      // 注意这个Export2Excel路径
      // const { export_json_to_excel } = require('@/vendor/Export2Excel');
      const data = formatJson(filterVal, listData);
      export_json_to_excel(tHeader, data, exportName);
    });
  },

  formatJson(filterVal, jsonData) {
    return jsonData.map(v => filterVal.map(j => v[j]))
  },
  formatDate(second, fmt, isMs) {
    if (!second || !fmt || isNaN(second)) {
      return ''
    }
    let date = new Date(isMs ? second : second * 1000)
    let tObj = {
      M: date.getMonth() + 1,
      d: date.getDate(),
      h: date.getHours(),
      m: date.getMinutes(),
      s: date.getSeconds()
    }
    fmt = fmt.replace(/y+/, date.getFullYear())
    for (let key in tObj) {
      if (new RegExp(`(${key}+)`).test(fmt)) {
        if (RegExp.$1.length == 1) {
          fmt = fmt.replace(RegExp.$1, tObj[key])
        } else {
          fmt = fmt.replace(
            RegExp.$1,
            ('00' + tObj[key]).slice((tObj[key] + '').length)
          )
        }
      }
    }
    return fmt
  }
}
export function parseTime(time, cFormat) {
  if (arguments.length === 0 || !time) {
    return null
  }
  const format = cFormat || '{y}-{m}-{d} {h}:{i}:{s}'
  let date
  if (typeof time === 'object') {
    date = time
  } else {
    if ((typeof time === 'string')) {
      if ((/^[0-9]+$/.test(time))) {
        // support "1548221490638"
        time = parseInt(time)
      } else {
        // support safari
        // https://stackoverflow.com/questions/4310953/invalid-date-in-safari
        time = time.replace(new RegExp(/-/gm), '/')
      }
    }

    if ((typeof time === 'number') && (time.toString().length === 10)) {
      time = time * 1000
    }
    date = new Date(time)
  }
  const formatObj = {
    y: date.getFullYear(),
    m: date.getMonth() + 1,
    d: date.getDate(),
    h: date.getHours(),
    i: date.getMinutes(),
    s: date.getSeconds(),
    a: date.getDay()
  }
  const time_str = format.replace(/{([ymdhisa])+}/g, (result, key) => {
    const value = formatObj[key]
    // Note: getDay() returns 0 on Sunday
    if (key === 'a') {
      return ['日', '一', '二', '三', '四', '五', '六'][value]
    }
    return value.toString().padStart(2, '0')
  })
  return time_str
}

/**
 * @param {number} time
 * @param {string} option
 * @returns {string}
 */
export function formatTime(time, option) {
  if (('' + time).length === 10) {
    time = parseInt(time) * 1000
  } else {
    time = +time
  }
  const d = new Date(time)
  const now = Date.now()

  const diff = (now - d) / 1000

  if (diff < 30) {
    return '刚刚'
  } else if (diff < 3600) {
    // less 1 hour
    return Math.ceil(diff / 60) + '分钟前'
  } else if (diff < 3600 * 24) {
    return Math.ceil(diff / 3600) + '小时前'
  } else if (diff < 3600 * 24 * 2) {
    return '1天前'
  }
  if (option) {
    return parseTime(time, option)
  } else {
    return (
      d.getMonth() +
      1 +
      '月' +
      d.getDate() +
      '日' +
      d.getHours() +
      '时' +
      d.getMinutes() +
      '分'
    )
  }
}

/**
 * @param {string} url
 * @returns {Object}
 */
export function param2Obj(url) {
  const search = decodeURIComponent(url.split('?')[1]).replace(/\+/g, ' ')
  if (!search) {
    return {}
  }
  const obj = {}
  const searchArr = search.split('&')
  searchArr.forEach(v => {
    const index = v.indexOf('=')
    if (index !== -1) {
      const name = v.substring(0, index)
      const val = v.substring(index + 1, v.length)
      obj[name] = val
    }
  })
  return obj
}

export function dataURLToBlob(dataurl) { //ie 图片转格式
  var arr = dataurl.split(','),
    mime = arr[0].match(/:(.*?);/)[1],
    bstr = atob(arr[1]),
    n = bstr.length,
    u8arr = new Uint8Array(n);
  while (n--) {
    u8arr[n] = bstr.charCodeAt(n);
  }
  return new Blob([u8arr], {
    type: mime
  })
}

export function downloadResult(name) {
  let canvasID = document.body
  let a = document.createElement('a');
  html2canvas(canvasID).then(canvas => {
    let dom = document.body.appendChild(canvas);
    dom.style.display = "none";
    a.style.display = "none";
    document.body.removeChild(dom);
    let blob = this.dataURLToBlob(dom.toDataURL("image/png"));
    a.setAttribute("href", URL.createObjectURL(blob));
    a.setAttribute("download", name + ".png")
    document.body.appendChild(a);
    a.click();
    URL.revokeObjectURL(blob);
    document.body.removeChild(a);
  });
}

export function printOut(name) {
  // 个人观察只是截取可见范围以及以下的区域，所以先将滚动条置顶
  $(window).scrollTop(0); // jQuery 的方法
  document.body.scrollTop = 0; // IE的
  document.documentElement.scrollTop = 0; // 其他
  this.downloadResult(name)
}
